package com.jlh.viewer.thread;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author mymx.jlh
 * @version 1.0.0 2018/4/21 10:26
 */
public class CacheBlock {

    public static class Cache<K,V>{
        //模拟redis
        private ConcurrentHashMap<K,FutureTask<V>> caches;



        public Cache() {
            this.caches = new ConcurrentHashMap<>();
        }

        public V get(K k, Compute<V> compute){
            FutureTask<V> res = caches.get(k);
            if (res == null){
                FutureTask<V> ft = new FutureTask<V>(compute::call);
                res = caches.putIfAbsent(k,ft);
                if (res == null){
                    res = ft;
                    res.run();
                }
            }

            try {
                return res.get(2,TimeUnit.SECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    @FunctionalInterface
    public interface Compute<V>{
        V call();
    }


    public static void main(String[] args) {
        Cache<String,String> caches = new Cache<>();
        String res = caches.get("jlh",()->"jiluohao");

        System.out.println(res);
    }
}
